package utils

import (
	"fmt"
	"ksirGo/global"
	"mime/multipart"
	"net/url"
	"path"
	"strings"
	"time"

	"github.com/google/uuid"
	"github.com/minio/minio-go/pkg/policy"
	"github.com/minio/minio-go/v7"
)

func CreateMinioBucket(bucketName string) {
	location := "us-east-1"

	if err := global.MINIO.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: location, ObjectLocking: false}); err != nil {
		exists, errBucketExists := global.MINIO.BucketExists(ctx, bucketName)
		if errBucketExists == nil && exists {
			fmt.Println(bucketName, " 存储桶已存在")
		} else {
			fmt.Println("创建存储桶异常：", err)
		}
	} else {
		fmt.Println("成功创建存储桶", bucketName)
	}
}

// 获取文件后缀名
func GetFileType(filePath string) (filetype string, filename string) {
	fileNameWithSuffix := path.Base(filePath)
	fileType := path.Ext(fileNameWithSuffix)
	fileNameOnly := strings.TrimSuffix(fileNameWithSuffix, fileType)
	return fileType, fileNameOnly
}

func UploadFileAvatar(file *multipart.FileHeader) (*string, *minio.UploadInfo, error) {
	reader, readerErr := file.Open()
	if readerErr != nil {
		return nil, nil, readerErr
	}
	filetype, _ := GetFileType(file.Filename)
	generate_file_name := uuid.New().String() + filetype
	// 规则： http://[minio域名]/[存储桶]/[文件名]
	image_url := fmt.Sprintf("http://%s:%d/%s/%s", global.CONFIG.MinIO.DeployHost, global.CONFIG.MinIO.DeployPort, "avatar", generate_file_name)
	uploadInfo, err := global.MINIO.PutObject(ctx, "avatar", generate_file_name, reader, file.Size, minio.PutObjectOptions{ContentType: "application/octet-stream"})
	return &image_url, &uploadInfo, err
}

func GetFileUrl(bucketName string, fileName string, expires time.Duration) (string, error) {
	reqParams := make(url.Values)
	presignedURL, err := global.MINIO.PresignedGetObject(ctx, bucketName, fileName, expires, reqParams)
	return presignedURL.String(), err
}

func InitBucket() {
	// 创建存储桶
	CreateMinioBucket("avatar")                                               // 头像存储桶
	global.MINIO.SetBucketPolicy(ctx, "avatar", policy.BucketPolicyReadWrite) // 设置存储桶为公开
}
